﻿using AutoMapper;
using BasicData.Domain;
using BasicData.ErrorCode;
using BasicData.Infrastrueturc.Command;
using BasicData.Infrastrueturc.Interfaces;
using BasicData.Write.API.Appplications.Commands;
using MediatR;

namespace BasicData.Write.API.Appplications.CommandHandlers
{
    /// <summary>
    /// 应用创建命令处理
    /// </summary>
    public class AppCreateCommandHandler : IRequestHandler<AppCreateCommand, APIResult<int>>
    {
        private readonly IBaseReposiotry<WF_Instance> InstanceRepository;
        private readonly IBaseReposiotry<WF_Record> recordReposiotry;
        private readonly IBaseReposiotry<WF_Setting> settingReposiotry;
        private readonly IBaseReposiotry<Room> roomReposiotry;
        private readonly ILogger<AppCreateCommandHandler> logger;
        private readonly IMapper mapper;
       
        public AppCreateCommandHandler(IBaseReposiotry<WF_Instance> InstanceRepository, IBaseReposiotry<WF_Record> recordReposiotry
            , IBaseReposiotry<Room> roomReposiotry, ILogger<AppCreateCommandHandler> logger, IMapper mapper,
            IBaseReposiotry<WF_Setting> settingReposiotry)
        {
            this.InstanceRepository = InstanceRepository;
            this.recordReposiotry = recordReposiotry;
            this.roomReposiotry = roomReposiotry;
            this.logger = logger;
            this.mapper = mapper;
            this.settingReposiotry = settingReposiotry;
        }



        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回引应用添加任务</returns>
        public async Task<APIResult<int>> Handle(AppCreateCommand request, CancellationToken cancellationToken)
        {


            APIResult<int> result=new APIResult<int>();
            result.Code=ResultCode.添加成功;
            result.Message=ResultCode.添加成功.ToString();
            using (var tran = InstanceRepository.DB.Database.BeginTransaction())
            {
                try
                {
                    if (string.IsNullOrEmpty(request.UserId) || string.IsNullOrEmpty(request.UserNickname))
                    {
                        throw new Exception("当前命令不完整，请联系管理员");
                    }
                  
                    DateTime now= DateTime.Now; 
                    #region 应用

                    Room room = mapper.Map<Room>(request);
                    await roomReposiotry.AddAsync(room);
                    #endregion

                    #region 实例
                    WF_Instance instance = new WF_Instance();
                    instance.InforId = room.RoomId;
                    instance.FlowStatus=(int)FlowStatus.已提交;
                    instance.FlowStatusName=FlowStatus.已提交.ToString();
                    instance.StarterId =Convert.ToInt32( request.UserId);
                    instance.StarterName=request.UserNickname;
                    //查询流程设置
                    var setting = settingReposiotry.GetAll().ToList();
                    instance.CurrentNodeNo= setting[0].NodeNo;
                    instance.CurrentNodeName= setting[0].NodeName;
                    instance.CurrentOperatorId= Convert.ToInt32(request.UserId);
                    instance.CurrentOperatorName= request.UserNickname;
                    instance.NextNodeNo= setting[1].NodeNo;
                    instance.NextNodeName= setting[1].NodeName;
                    instance.NextOperatorId= setting[1].UserId;
                    instance.NextOperatorName = setting[1].UserNickName;
                    instance.CreateTime= now;
                    await InstanceRepository.AddAsync(instance);
                    #endregion
                    #region 流转记录
                    WF_Record record = new WF_Record();
                    record.InstanceId = instance.InstanceId;
                    record.NodeNo=instance.CurrentNodeNo;
                    record.NodeName= instance.CurrentNodeName;
                    record.OperatorId=instance.CurrentOperatorId;
                    record.OperatorName=instance.CurrentOperatorName;
                    record.OperatorOpinion = "";
                    record.ApproveStatus= (int)ApproceStatues.已提交;
                    record.ApproveStatusName=ApproceStatues.已提交.ToString();
                    record.CreateTime= now;
                    await recordReposiotry.AddAsync(record);

                    #endregion




                    tran.Commit();
                }
                catch (Exception ex)
                {
                    result.Code = ResultCode.添加失败;
                    result.Message = ResultCode.添加失败.ToString()+ex.Message;
                    logger.LogError("创建应用时报错" + ex.Message);
                    tran.Rollback();
                }
            }



                return await Task.FromResult(result);
        }
    }
}
